<template>
  <div class="device-add">
    <DynamicForm ref="dynamicFormRef" @click="callBack" :refresh="state.refresh" labelWidth="180px"
                 :rulesForm="state.deviceAddForm" :rules="state.deviceRules"/>
  </div>
</template>

<script lang="ts" setup>

import {ref, onMounted, reactive, defineEmits} from 'vue';

import DynamicTable from '@/components/layout/table/dynamic-table.vue';
import DynamicForm from '@/components/layout/form/dynamic-form.vue';

import {deviceAddForm, deviceRules} from '@/assets/script/middle/forms/device/device-form';
import {listOrganizationApi} from "@/api/organization";
import {listConstByDictionaryCodesApi} from "@/api/dictionary";
import {findDeviceSpecByIdApi, findPageListApi} from "@/api/product";
import {findDeviceByIdApi, insertDeviceApi, modifyDeviceApi} from "@/api/device";
import {ElMessage} from "element-plus";
import {useRoute} from "vue-router";

const dynamicTableRef = ref(DynamicTable);
const dynamicFormRef = ref(DynamicForm);
const route = useRoute();

const emits = defineEmits<{ (e: "appClick", data: object): void }>();

const state = reactive({
  deviceAddForm: JSON.parse(JSON.stringify(deviceAddForm)),
  deviceRules: deviceRules,
  spec: [] as any,
  refresh: 0,
  device: {} as any,
  organization: [] as any
})

onMounted(() => {
  const card = state.deviceAddForm[0].card
  const status = card.find(({name = ''}) => name == 'status')
  status['status'] = '0'
  listDictionary(['device', 'device_form']);
  listOrganization({deleted: 0});
  findPageList();

  if (route.query && route.query.id) {
    findDeviceById({id: route.query.id})
  }
})

const callBack = (data: any) => {
  const dataForm = dynamicFormRef.value.getData()
  switch (data.type || '') {
    case 'submit':
      // eslint-disable-next-line no-case-declarations
      let params = data.data;
      if (params['deviceType'] === 'mattress' && !params['formCode']) {
        ElMessage.success({message: '设备形态不能为空！'})
        return false;
      }
      if (params['organizationId']) {
        const organization = state.organization.find(({organizationId = ''}) => organizationId == params['organizationId'])
        params['topOrganizationId'] = organization?.parentId ? organization?.parentId : organization?.id
      }
      if (params['specIdName']) {
        params['specName'] = params['specIdName']
      }
      if (params['organizationIdName']) {
        params['organizationName'] = params['organizationIdName']
      }
      if (params['constCodeName']) {
        params['constName'] = params['constCodeName']
      }
      if (params['formCodeName']) {
        params['formName'] = params['formCodeName']
      }

      if (state.device && state.device.id) {
        params['id'] = state.device.id
        modifyDeviceApi(params).then((data: any) => {
          if (data.code === 0) {
            ElMessage.success({message: '修改成功！'})
            emits('appClick', {type: 'closeTab', data: route.path})
          } else {
            ElMessage.success({message: '修改失败！'})
          }
        })
      } else {
        params['bindStatus'] =0
        insertDeviceApi(params).then((data: any) => {
          if (data.code === 0) {
            ElMessage.success({message: '添加成功！'})
            emits('appClick', {type: 'closeTab', data: route.path})
          } else {
            ElMessage.success({message: '添加失败！'})
          }
        })
      }
      break
    case 'specId':
      // eslint-disable-next-line no-case-declarations
      const card = state.deviceAddForm[0].card
      for (let key in dataForm) {
        const item = card.find(({name = ''}) => name === key)
        item[key] = dataForm[key]
      }
      // eslint-disable-next-line no-case-declarations
      let {longs = null, wide = null, high = null} = state.spec.find(({id = ''}) => id === data.data)
      if (!dataForm['longs']) {
        const longsCard = card.find(({name = ''}) => name == 'longs')
        longsCard['longs'] = longs
      }
      if (!dataForm['wide']) {
        const wideCard = card.find(({name = ''}) => name == 'wide')
        wideCard['wide'] = wide
      }
      if (!dataForm['high']) {
        const highCard = card.find(({name = ''}) => name == 'high')
        highCard['high'] = high
      }
      if (card) {
        const functions = card?.find(({name = ''}) => name == 'functions')
        findDeviceSpecById({id: data.data}, functions)
      }
      state.refresh = Math.random()
      break
  }
}

const findDeviceSpecById = (params: any, item: any) => {
  findDeviceSpecByIdApi(params).then((data: any) => {
    if (!data) {
      return
    }
    const functions = data.functionList
    functions?.forEach(({functionName = null}) => {
      if (item['functions']) {
        item['functions'] += '，';
      }
      item['functions'] += functionName
    })
  })
}

const listOrganization = (params: any) => {
  listOrganizationApi(params).then((data: any) => {
    state.organization = data
    const card = state.deviceAddForm[0].card
    const organization = card.find(({name = ''}) => name == 'organizationId')
    data.forEach(({name = '', id = ''}) => {
      organization.options.push({label: name, value: id})
    })
  })
}

const listDictionary = (params: any) => {
  listConstByDictionaryCodesApi(params).then((data: any) => {
    const card = state.deviceAddForm[0].card
    const deviceType = card.find(({name = ''}) => name == 'constCode')
    const formType = card.find(({name = ''}) => name == 'formCode')
    data.forEach(({constCode = '', constName = '', dictionaryCode = ''}) => {
      switch (dictionaryCode) {
        case 'device':
          if (constCode && constName) {
            deviceType.options.push({label: constName, value: constCode})
          }
          break
        default:
          if (constCode && constName) {
            formType.options.push({label: constName, value: constCode})
          }
          break
      }
    })
  })
}

const findPageList = (params = {pageSize: 200}) => {
  findPageListApi(params).then((data: any) => {
    const card = state.deviceAddForm[0].card
    const spec = card.find(({name = ''}) => name == 'specId')
    state.spec = data.data
    data.data.forEach(({id = '', specName = ''}) => {
      spec.options.push({label: specName, value: id})
    })
  })
}

const findDeviceById = (params: any) => {
  findDeviceByIdApi(params).then((data: any) => {
    state.device = data
    const card = state.deviceAddForm[0].card
    const spec = state.spec.find(({id = ''}) => id === data.specId)
    let {longs = null, wide = null, high = null} = spec || {longs: null, wide: null, high: null}
    card?.forEach((e: any) => {
      if (!e.line) {
        e[e.name] = data[e.name]
      }
    })
    state.refresh = Math.random()
    console.log('findDeviceByIdApi', card)
  })
}

</script>